﻿using System;
using NHibernate;

namespace Inovout.Data.Repository
{
    public class TransactionTracker : IDisposable
    {
        private bool disposed;
        public ExceptionContext ExceptionContext { get; private set; }
        public TransactionTracker(ExceptionContext exceptionContext)
        {
            this.ExceptionContext = exceptionContext;
        }
        public ITransaction CurrentTransaction { get; private set; }
        public ISession Session { get; private set; }
        public void BeginTransaction(ISession session)
        {
            this.Session = session;
            CurrentTransaction = session.BeginTransaction();
        }
        public void Dispose()
        {
            if (disposed) return;

            disposed = true;

           if (CurrentTransaction == null)
            {
                return;
            }
            try
            {
                if (this.ExceptionContext.IsException)
                {
                    CurrentTransaction.Rollback();
                }
                else
                {
                    CurrentTransaction.Commit();
                }
            }
            catch (Exception ex)
            {
                Session.Close();
                throw ex;
            }
        }
    }
}